// 负责创建和管理 BrowerWindow
const { BrowserWindow, shell } = require('electron')
import { join } from 'path'
import { is } from '@electron-toolkit/utils'
import icon from '../../../../resources/icon.png?asset'

export function createMainWindow() {
  // 创建窗口对象
  const mainWindow = new BrowserWindow({
    width: 900,
    maxWidth: 1125,
    minWidth: 300,
    height: 670,
    minHeight: 500,
    show: false,
    frame: false, // 无边框窗口
    autoHideMenuBar: true,
    icon: icon,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      // 在js中使用nodejs api
      nodeIntegration: true,
      contextIsolation: false
    }
  })

  // 去掉菜单栏
  mainWindow.removeMenu()

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  if (is.dev && process.env['ELECTROM_RENDRER_URL']) {
    mainWindow.loadURL(process.env['ELECTROM_RENDRER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  return mainWindow
}

// 创建子窗口对象
export function createNoteWindow(len, theme, noteTheme) {
  const noteWindow = new BrowserWindow({
    width: 300,
    minWidth: 250,
    height: 400,
    minHeight: 350,
    show: false,
    frame: false, // 无边框窗口
    autoHideMenuBar: true,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      // 在js中使用nodejs api
      nodeIntegration: true,
      contextIsolation: false
    }
  })
  // 去掉菜单栏
  noteWindow.removeMenu()

  noteWindow.on('ready-to-show', () => {
    noteWindow.show()
  })

  noteWindow.loadURL(
    `file://${__dirname}/../renderer/index.html#/note/${len}?theme=${theme}&noteTheme=${noteTheme}`
  )

  return noteWindow
}
